package com.cmcc.linlaker.ui.query;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.cmcc.linlaker.R;
import com.cmcc.linlaker.fragment.RoundFragment;
import com.cmcc.linlaker.ui.query.fragment.ProjectBaseDetailFragment;
import com.cmcc.linlaker.utils.BarUtils;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.view.ExitDialog;
import com.tianditu.android.maps.GeoPoint;
import com.tianditu.android.maps.MapController;
import com.tianditu.android.maps.MapView;
import com.tianditu.android.maps.MyLocationOverlay;
import com.tianditu.android.maps.TErrorCode;
import com.tianditu.android.maps.TGeoAddress;
import com.tianditu.android.maps.TGeoDecode;
import com.tianditu.android.maps.overlay.CircleOverlay;
import com.tianditu.android.maps.overlay.MarkerOverlay;
import com.tianditu.android.maps.renderoption.CircleOption;
import com.tianditu.android.maps.renderoption.DrawableOption;

import javax.microedition.khronos.opengles.GL10;

public class ModifyAddressActivity extends AppCompatActivity {
    private String address;

    @Nullable
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_address);

        RoundFragment.isEnterModifyAddress = true;
        BarUtils.initStatusBar(this);

        initView();
    }

    private EditText edit_address;
    private MapView mMapView;

    private void initView() {
        address = getIntent().getStringExtra("address");
        edit_address = findViewById(R.id.edit_address);
        edit_address.setText(address);
        mMapView = findViewById(R.id.main_map);

        initMap();
    }

    public MyLocationOverlay mMyLocation;
    private GeoPoint mPoint;
    private MapController mMapController;
    private boolean isCanUpload = true;
    private int currentZoom = 13;

    private void initMap() {
        //得到mMapView的控制权,可以用它控制和驱动平移和缩放
        mMapController = mMapView.getController();
        //设置地图zoom级别
        mMapController.setZoom(13);
        //设置启用内置的缩放控件
        mMapView.setBuiltInZoomControls(false);
        mMapView.setMaxZoomLevel(15);
        mMapView.setScaleChangeListener(new MapView.OnScaleChangeListener() {
            @Override
            public void onScaleChange() {
                int zoom = mMapView.getZoomLevel();
                if (zoom >= 15) {
                    mMapController.setZoom(15);
                }

                if (zoom != currentZoom) {
                    isCanUpload = false;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isCanUpload = true;
                        }
                    }, 2000);
                }
                currentZoom = zoom;
            }
        });
        mMapView.setMapType(MapView.TMapType.MAP_TYPE_VEC);
        mMapView.setLogoPos(MapView.LOGO_LEFT_TOP);

        mMyLocation = new MyAddressOverlay(this, mMapView);
        mMyLocation.enableMyLocation();
        mMapView.addOverlay(mMyLocation);

        drawCenter();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMyLocation.isCompassEnabled()) {
            mMyLocation.disableCompass();
        }

        if (mMyLocation.isMyLocationEnabled()) {
            mMyLocation.disableMyLocation();
        }
    }


    private GeoPoint lastGeoPoint;

    class MyAddressOverlay extends MyLocationOverlay {
        public MyAddressOverlay(Context context, MapView mapView) {
            super(context, mapView);
        }

        /*
         * 处理在"我的位置"上的点击事件
         */
        protected boolean dispatchTap() {
            return true;
        }

        private long mExitTime;

        @Override
        public void onLocationChanged(Location location) {
            super.onLocationChanged(location);

            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                mExitTime = System.currentTimeMillis();

                GeoPoint geoPoint = mMapView.getMapCenter();
                if (lastGeoPoint != null) {
                    if (lastGeoPoint.getLongitudeE6() != geoPoint.getLongitudeE6() && lastGeoPoint.getLatitudeE6() != geoPoint.getLatitudeE6()) {
                        if (isCanUpload) {
                            search(geoPoint);
                        }
                    }
                } else {
                    if (isCanUpload) {
                        search(geoPoint);
                    }
                }
                lastGeoPoint = geoPoint;
            }
        }

        @Override
        protected void drawMyLocation(GL10 gl, MapView mapView, Location lastFix, GeoPoint myLocation, long when) {
        }
    }

    /**
     * 绘制中心点
     */
    private void drawCenter() {
        DrawableOption option = new DrawableOption();
        option.setAnchor(0.5f, 0.5f);
        MarkerOverlay mMarker = new MarkerOverlay();
        mMarker.setOption(option);
        mMarker.setIcon(getResources().getDrawable(R.mipmap.location_icon2));
        mMapView.addOverlay(mMarker);

        mPoint = mMyLocation.getMyLocation();
        mMarker.setPosition(mPoint);
        mMapController.setCenter(mPoint);
        mMapController.animateTo(mPoint);

        addCircle(mPoint);
    }

    private CircleOverlay overlay;

    /**
     * 圆形
     */
    private void addCircle(GeoPoint mPoint) {
        CircleOption option = new CircleOption();
        option.setFillColor(0x440091FF);
        option.setStrokeWidth(1);
        option.setStrokeColor(0xFF3A9CE6);

        overlay = new CircleOverlay();
        overlay.setOption(option);
        overlay.setCenter(mPoint);
        overlay.setRadius(2000);
        mMapView.addOverlay(overlay);
    }

    public void back(View view) {
        finish();
    }

    public void confirm(View view) {
        final String address = edit_address.getText().toString();
        if (TextUtils.isEmpty(address)) {
            ToastUtils.showText(this, "请选择或输入修正地址");
            return;
        }

        ExitDialog dialog = new ExitDialog(this, R.style.dialog);
        dialog.setOnConfirmClickListener(new ExitDialog.OnConfirmClickListener() {
            @Override
            public void onConfirmClick() {
                ProjectBaseDetailFragment.addressBean.address = address;
                ProjectBaseDetailFragment.addressBean.latitude = latitude;
                ProjectBaseDetailFragment.addressBean.longitude = longitude;

                setResult(1000);
                finish();
            }
        });
        dialog.show();

        dialog.setContent("确认要修正地址吗?");

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }


    private void search(GeoPoint mPoint) {
//        Log.e("latitude", Utils.formatLatLng((float) (latitude / 1E6)));
//        Log.e("longitude", Utils.formatLatLng((float) (longitude / 1E6)));

        latitude = mPoint.getLatitudeE6();
        longitude = mPoint.getLongitudeE6();

        TGeoDecode tGeoDecode = new TGeoDecode(new TGeoDecode.OnGeoResultListener() {
            @Override
            public void onGeoDecodeResult(TGeoAddress tGeoAddress, int errorCode) {
                if (TErrorCode.OK == errorCode) {
                    // 查询点相关信息
                    String formatAddress = tGeoAddress.getFullName();
                    edit_address.setText(formatAddress);
                } else {
                    System.out.println("查询出错：" + errorCode);
                }
            }
        });
        tGeoDecode.search(mPoint);
    }

    private double latitude, longitude;
}
